using System.Collections;
using UnityEngine;

public class CheckPointOnContact : MonoBehaviour
{
	public GameObject spawnPointObject;

	public Vector3 spawnPosition;

	public Quaternion spawnRotation;

	public int checkPointNumber = -1;

	private float activationDelay = 1.2f;

	public bool useDelay = true;

	private bool isActive;

	private bool willActivate;

	private void Start()
	{
		Object.Destroy(base.GetComponent<Renderer>());
		Object.Destroy(base.gameObject.GetComponent<MeshFilter>());
		if (BallBehaviour.GetInstance() == null)
		{
			base.GetComponent<Collider>().enabled = false;
		}
	}

	private void Awake()
	{
		LevelController.LevelReadyEvent += OnLevelReady;
		BallBehaviour.BallResetEvent += OnBallReset;
		LevelEnd.LevelEndEnterEvent += OnLevelEndEnter;
	}

	private void OnDestroy()
	{
		LevelController.LevelReadyEvent -= OnLevelReady;
		BallBehaviour.BallResetEvent -= OnBallReset;
		LevelEnd.LevelEndEnterEvent -= OnLevelEndEnter;
	}

	private void OnLevelReady(Transform levelTransform)
	{
		if (base.transform.root == levelTransform)
		{
			Initialize();
		}
	}

	private void OnLevelEndEnter(GameObject levelEnd)
	{
		if (willActivate)
		{
			willActivate = false;
		}
	}

	private void Initialize()
	{
		spawnPosition = spawnPointObject.transform.position;
		spawnRotation = spawnPointObject.transform.rotation;
		Object.Destroy(spawnPointObject);
		isActive = true;
	}

	private void OnTriggerEnter(Collider other)
	{
		if (isActive && other.gameObject == BallBehaviour.GetInstance().gameObject)
		{
			StartCoroutine(ActivateCO());
		}
	}

	private void OnBallReset()
	{
		if (willActivate)
		{
			willActivate = false;
		}
	}

	private IEnumerator ActivateCO()
	{
		willActivate = true;
		if (useDelay)
		{
			yield return new WaitForSeconds(activationDelay);
		}
		while (BallBehaviour.GetInstance().isAirborne)
		{
			yield return null;
		}
		if (willActivate)
		{
			willActivate = false;
			Activate();
		}
	}

	private void Activate()
	{
		SpawnPoint.SetPosition(spawnPosition);
		SpawnPoint.SetRotation(spawnRotation);
		Game.FireCheckpointActivatedEvent(checkPointNumber);
	}
}
